﻿/***************************************************************
*    
*     JS对象prototype的扩展
*     公共方法
*
* **************************************************************/

///#region Common Function
function hasValue(value) {
    /// <summary>判断对象是否为空，常用于数据值的空判断</summary>
    /// <param name="value" type="Object">判断的值</param>
    /// <returns type="Bool" />
    return (value != undefined && value != null);
}
function strNotEmpty (value) {
    /// <summary>判断String是否为空,或是空白串(trim处理)</summary>
    /// <param name="value" type="String">判断的值</param>
    /// <returns type="Bool" />
    return (hasValue(value) && value.trim().length > 0)
}
function getStringValue(value) {
    /// <summary>将对象转换成String，为空时返回''</summary>
    /// <param name="value" type="Object">传入的对象</param>
    /// <returns type="String" />
    return value ? value + '' : '';
}
function getJsonValue (data, propname) {
    /// <summary>获取单条数据data中属性名为propname的值,出错时返回''</summary>
    /// <param name="data" type="Json">Json数据单行对象</param>
    /// <param name="propname" type="String">属性名</param>
    /// <returns type="Object" />
    if (propname && propname.length > 0)
        return new Function('data', 'return hasValue(data.' + propname + ') ? data.' + propname + ' :null;').call(this, data);
    return null;
}
function getRangeValue(value, min, max) {
    /// <summary>比较value，获取范围内数据</summary>
    /// <param name="value" type="Object">值</param>
    /// <param name="min" type="Object">最小值</param>
    /// <param name="max" type="Object">最大值</param>
    /// <returns type="Object" />
    if (value < min)
        value = min;
    else if (value > max)
        value = max;
    return value;
}
function getUrlParamStr() {
    /// <summary>获取url参数字串</summary>
    var url = window.location.href, index = url.indexOf('?');
    if (index > 0) {
       return url.substr(index);
   }
   return '';
}
function getUrlParam() {
    /// <summary>获取Url参数</summary>
    /// <returns type="Json" />
    var url = unescape(window.location.href);
    var index = url.indexOf('#');
    if (index > 0)
        url = url.substring(0, index);
    index = url.indexOf('?');
    if (index > 0 && index < url.length) {
        var allargs = url.split("?")[1];
        if (allargs) {
            var args = allargs.split("&");
            var sbParam = new StringBuilder();
            for (var i = 0; args[i]; i++) {
                var arg = args[i].split("=");
                if (arg[0] != 'ram')
                    sbParam.append('"').append(arg[0]).append('":"').append(arg[1]).append('"').append(',');
            }
            if (sbParam.isNotEmpty()) {
                return $.parseJSON('{' + sbParam.removeLast().append('}').toString());
            }
        }
    }
    return null;
}
function getSaveText(text) {
    /// <summary>获取需要保存的文本，对文本内容进行格式化</summary>
    /// <param name="text" type="String">文本值</param>
    /// <returns type="String" />
    text = text.replace(/\\/g, '\\\\').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return text.replace(/"/g, '\\"');
    
}
///#endregion

///#region 数据验证
function isInteger(value){
    /// <summary>检查是否为整数</summary>
    /// <param name="value" type="String">值</param>
    /// <returns type="Bool" />
    return regTest(iconfig.validator.rules.int,value);
}
function isFloat(value, fraction) {
    /// <summary>检查是否为Float</summary>
    /// <param name="value" type="String">值</param>
    /// <param name="fraction" type="Number">小数位数</param>
    /// <returns type="Bool" />
    if (!hasValue(fraction))
        fraction = iconfig.format.decimalfraction;
    return regTest(iconfig.validator.rules.float.replace('[p]', fraction), value);
}
function regTest(reg, value) {
    /// <summary>运行正则进行test验证</summary>
    /// <param name="reg" type="String">正则表达式</param>
    /// <param name="value" type="String">验证的值</param>
    /// <returns type="Bool" />
    var reg = new RegExp(reg);
    return reg.test(value);
}
///#endregion

///#region 数据格式化
formatString = function (type, value, format) {
    /// <summary>对String进行格式化,为空时返回''</summary>
    /// <param name="type" type="String">格式类型</param>
    /// <param name="value" type="String">格式化的值</param>
    /// <param name="format" type="String || Number">【非必要属性】,格式化配置</param>
    /// <returns type="Object" />
    if (hasValue(value)) {
        if (type) {
            switch (type) {
                //                case "int":   
                //                    break;   
                case "num":
                    value = toDecimal(value, format);
                    break;
                case "cur":
                    value = toDecimal(value, format);
                    break;
                case "date":
                    value = toDateStr(value, false, format);
                    break;
                case "datetime":
                    value = toDateStr(value, true, format);
                    break;
                case "bool":
                    value = toBool(value);
                    break;
            }
        }
        return value;
    }
    else
        return '';
}
formatStringForView = function (type, value, format) {
    /// <summary>将String格式化成显示的html格式,为空时返回''</summary>
    /// <param name="type" type="String">格式类型</param>
    /// <param name="value" type="String">格式化的值</param>
    /// <param name="format" type="String">【非必要属性】,格式化配置</param>
    /// <returns type="Object" />
    if (hasValue(value)) {
        switch (type) {
            //                case "int":   
            //                    break;   
            case "num":
                value = toDecimal(value, format);
                break;
            case "cur":
                value = toDecimal(value, format);
                break;
            case "date":
                value = toDateStr(value, false, format);   
                break;   
            case "datetime":
                value = toDateStr(value, true, format);   
                break;   
            case "bool":
                value = toBoolView(value,true);
                break;
            case "enum":
                value = toEnum(value,format);
                break;
        }
        return value;
    }
    else
        return '';
}

///#region 日期处理
function toDateStr(value, showtime, format) {
    /// <summary>将数据转换成日期格式字串,为空时返回''</summary>
    /// <param name="value" type="String||Date">格式化的值</param>
    /// <param name="showtime" type="Bool">【非必要属性】,是否显示时间</param>
    /// <param name="format" type="String">【非必要属性】,格式化配置</param>
    /// <returns type="String" />
    value = toDate(value, showtime);
    if (value)
        return value.format(format || (showtime ? iconfig.format.datetime : iconfig.format.date))
    return '';
}
function jsonToDate(value) {
    /// <summary>将json格式的时间换成日期格式</summary>
    /// <param name="value" type="String">值必须为json格式的时间</param>
    /// <returns type="Date" />
    if (hasValue(value))
        return new Date(Date.parse(value));
    return null;
}
function toDate(value, showtime) {
    /// <summary>将数据换成日期格式</summary>
    /// <param name="value" type="String">格式化的值</param>
    /// <param name="showtime" type="Bool">【非必要属性】,是否显示时间</param>
    /// <returns type="Date" />
    var type = typeof (value), date = null;
    if (type === 'date')
        return value;
    else {
        if (type === 'string') {
            date = showtime ? value.toDateTime() : value.toDate();
            if (!date)
                date = jsonToDate(value);
        }
    }
    return date;
}
function toDateNum(value) {
    /// <summary>将日期转换成日期数字</summary>
    /// <param name="value" type="Date">值</param>
    /// <returns type="Number" />
    if (hasValue(value)) {
        value = value.toDateTime();
        if (value)
            return Date.parse(value);
    }
    return null;
}
///#endregion

///#region 其他类型
function toDecimal(value, fraction) {
    /// <summary>将数据转换成Decimal格式,为空时返回''</summary>
    /// <param name="value" type="String">值</param>
    /// <param name="fraction" type="Number">【非必要属性】,小数位，为空时，使用系统统一格式</param>
    /// <returns type="Float" />
    if (value) {
        if (!hasValue(fraction))
            fraction = iconfig.format.decimalfraction;
        return parseFloat(value).toFixed(fraction);
    }
    return '';
}
function toBoolView(value, ishtml) {
    /// <summary>将数据转换成Bool显示格式(可以是html格式),为空时返回''</summary>
    /// <param name="value" type="String||Number">值</param>
    /// <param name="ishtml" type="Bool">【非必要属性】,是否为html格式</param>
    /// <returns type="String" />
    value = toBool(value);
    if (value !== '')
        return ishtml ? $iconst.Enum.boolhtm[value].Value : $iconst.Enum.bool[value].Value;
    return '';
}
function toBool(value) {
    /// <summary>将数据转换成Bool(0,1)值,为空时返回''</summary>
    /// <param name="value" type="String||Number">值</param>
    /// <returns type="Number" />
    if (hasValue(value) && value !== '') {
        if (typeof (value) == 'string')
            value = value.toLowerCase() == 'true';
        return value ? 1 : 0;
    }
    return '';
}
function toEnum(value, ename) {
    /// <summary>将数据转换成Enum文本,为空时返回''</summary>
    /// <param name="value" type="String">值</param>
    /// <param name="ename" type="String">枚举名称</param>
    /// <returns type="Object" />
    if (hasValue(value))
        return $sw.getEnumText(ename, value);
    return '';
}
function formatNum(value, len) {
    value += '';
    for (var i = value.length; i < len; i++) {
        value = '0' + value;
    }
    return value;
}
///#endregion
///#endregion

///#region StringBuilder对象
StringBuilder = function(value){
/// <summary>定义StringBuilder对象</summary>
/// <param name="value" type="String">值</param>
    this.strings = new Array();
    if (value && value.length > 0)
    this.append(value);
}

StringBuilder.prototype.append = function (value){
/// <summary>添加字符串</summary>
/// <param name="value" type="String">合并的数据</param>
/// <returns type="StringBuilder" />
    if (value && value.length > 0)
        this.strings.push(value);
    return this;
}
StringBuilder.prototype.isNotEmpty = function (){
/// <summary>是否为空</summary>
/// <returns type="Bool" />
    return this.strings.length > 0;
}
StringBuilder.prototype.clear = function (){
/// <summary>清空内容</summary>
    this.strings.length = 0;
}

StringBuilder.prototype.toString = function (split){
    /// <summary>转换为字符串返回</summary>
    /// <param name="split" type="String">分割字符</param>
    /// <returns type="String" />
    return this.strings.join(split || "");
}
StringBuilder.prototype.removeLast = function (){
/// <summary>删除最后一个添加的对象</summary>
/// <returns type="StringBuilder" />

    this.strings = this.strings.slice(0, -1);
    return this;
}
///#endregion

///#region String
String.prototype.format = function () {
    /// <summary>占位符的string格式化</summary>
    /// <returns type="String" />
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function (m, i) {
            return args[i];
        });
}
String.format = function () {
    /// <summary>占位符的string格式化</summary>
    /// <returns type="String" />
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}
String.prototype.trim = function () {
    /// <summary>去空</summary>
    /// <returns type="String" />
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.Replace = function (oldstr, newstr) {
    /// <summary>扩展replace方法</summary>
    /// <param name="oldstr" type="String">被替换的字符</param>
    /// <param name="newstr" type="String">替换的字符</param>
    /// <returns type="String" />
    return this.replace(new RegExp(oldstr, "gm"), newstr);
}
String.prototype.toDate = function () {
    /// <summary>String转换成日期</summary>
    /// <returns type="Date" />
    var result = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
    if (result) {
        var date = new Date(result[1], result[3] - 1, result[4]);
        if (date.getFullYear() == result[1] && date.getMonth() + 1 == result[3] && date.getDate() == result[4])
            return date;
    }
    return null;
}
String.prototype.toDateTime = function () {
    /// <summary>String转换成日期时间</summary>
    /// <returns type="DateTime" />
    var result = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/); //匹配yyyy-MM-dd:hh:mm:ss
    var hh, mm, ss;
    if (result) {
        hh = result[5];
        mm = result[6];
        ss = result[7];
    }
    else {
        result = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2})$/);  //匹配yyyy-MM-dd:hh:mm
        if (result) {
            hh = result[5];
            mm = result[6];
            ss = 0;
        }
        else {
            result = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); //匹配yyyy-MM-dd
            if (result)
                hh = mm = ss = 0;
        }
    }
    if (result) {
        var d = new Date(result[1], result[3] - 1, result[4], hh, mm, ss);
        if (d.getFullYear() == result[1] && (d.getMonth() + 1) == result[3] && d.getDate() == result[4] &&
        d.getHours() == hh && d.getMinutes() == mm && d.getSeconds() == ss)
            return d;
    }
    return null;
}
///#endregion

///#region Date
Date.prototype.format = function (format) {
    ///<summary>格式化日期</summary>
    ///<param name="format">日期格式字串，为空则为系统默认格式</param>
    /// <returns type="Date" />
    if (!format)
        format = iconfig.format.date;
    var o = {
        "M+": this.getMonth() + 1, //month 
        "d+": this.getDate(),    //day 
        "h+": this.getHours(),   //hour 
        "m+": this.getMinutes(), //minute 
        "s+": this.getSeconds(), //second 
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter 
        "S": this.getMilliseconds() //millisecond 
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
      RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
function isSameDay(d1, d2) {
    ///<summary>是否为同一天</summary>
    /// <param name="d1" type="Date">比较日期1</param>
    /// <param name="d2" type="Date">比较日期2</param>
    /// <returns type="Bool" />
    if(d1 && d2)
    return d1.getFullYear() === d2.getFullYear() &&
			d1.getMonth() == d2.getMonth() &&
			d1.getDate() == d2.getDate();
return false;
}
function getDayNum(year, month) {
    ///<summary>获取月份中的天数</summary>
    /// <param name="year" type="Number">年份</param>
    /// <param name="month" type="Number">月份</param>
    /// <returns type="Number" />
    return 32 - new Date(year, month, 32).getDate();
}
///#endregion

///#region file
function getFileName(file) {
    ///<summary>获取文件名</summary>
    /// <param name="file" type="String">文件全名</param>
    /// <returns type="String" />
    return file.replace(/.*(\/|\\)/, "");
}
function getFileExtName(file) {
    ///<summary>获取文件扩展名</summary>
    /// <param name="file" type="String">文件全名</param>
    /// <returns type="String" />
    return  (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase())[0] : '';
}	
///#endregion

///#region encode
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

function encode(str) {
    ///<summary>加密</summary>
    /// <param name="str" type="String">需要加密的字串</param>
    /// <returns type="String" />
    var out, i, len;
    var c1, c2, c3;

    len = str.length;
    i = 0;
    out = "";
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
}

function decode(str) {
    ///<summary>解密</summary>
    /// <param name="str" type="String">需要解密的字串</param>
    /// <returns type="String" />
    var c1, c2, c3, c4;
    var i, len, out;

    len = str.length;
    i = 0;
    out = "";
    while (i < len) {
        /* c1 */
        do {
            c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
        } while (i < len && c1 == -1);
        if (c1 == -1)
            break;

        /* c2 */
        do {
            c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
        } while (i < len && c2 == -1);
        if (c2 == -1)
            break;

        out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

        /* c3 */
        do {
            c3 = str.charCodeAt(i++) & 0xff;
            if (c3 == 61)
                return out;
            c3 = base64DecodeChars[c3];
        } while (i < len && c3 == -1);
        if (c3 == -1)
            break;

        out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

        /* c4 */
        do {
            c4 = str.charCodeAt(i++) & 0xff;
            if (c4 == 61)
                return out;
            c4 = base64DecodeChars[c4];
        } while (i < len && c4 == -1);
        if (c4 == -1)
            break;
        out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
    }
    return out;
}
///#endregion


